//
//  HomeViewController.m
//  PetApp
//
//  Created by apple on 16/3/9.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HomeViewController.h"
#import "SearchViewController.h"
#import "CaptrueViewController.h"
#import "CellOfRecommend.h"
#import "LikeOfCell.h"
#import "NewsOfCell.h"
#import "DetailOfPageViewController.h"
#import "ActivityViewController.h"
#import "FindViewController.h"
#import "BeLostViewController.h"
#import "MyOfUserDetail.h"
#import "LoginVC.h"
#import "RESideMenu.h"


#define WIDTH [UIScreen mainScreen].bounds.size.width


@interface HomeViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, readonly, retain) RESideMenu *sideMenuViewController;

@property (nonatomic, retain) UISegmentedControl *sg;

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) UIView *grayLine;

@end

@implementation HomeViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"PushVC"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"PushLVView"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"PushLoginVC"];
    [_grayLine release];
    [_collectionView release];
    [_sg release];
    [super dealloc];
}

- (RESideMenu *)sideMenuViewController {
    UIViewController *iter = self.parentViewController;
    while (iter) {
        if ([iter isKindOfClass:[RESideMenu class]]) {
            return (RESideMenu *)iter;
        } else if (iter.parentViewController && iter.parentViewController != iter) {
            iter = iter.parentViewController;
        } else {
            iter = nil;
        }
    }
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createNaviController];
    [self createSubViews];
    [self createNotification];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIView animateWithDuration:0.5 animations:^{
        self.grayLine.alpha = 1;
    }];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.grayLine.alpha = 0;
    

}

- (void)createNotification {


    [[NSNotificationCenter defaultCenter] addObserverForName:@"PushVC" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        DetailOfPageViewController *detailVC = [[DetailOfPageViewController alloc] init];
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
        [detailVC release];
        detailVC.tid = [note.userInfo objectForKey:@"tid"];
        
        
    }];
    [[NSNotificationCenter defaultCenter] addObserverForName:@"PushLVView" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if ([note.object isEqualToString:@"1"]) {
            BeLostViewController *belostVC = [[BeLostViewController alloc] init];
            belostVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:belostVC animated:YES];
            [belostVC release];
            belostVC.URLDic = note.userInfo;            
            
        }else if ([note.object isEqualToString:@"2"]) {

            ActivityViewController *activityVC = [[ActivityViewController alloc] init];
            activityVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:activityVC animated:YES];
            [activityVC release];
            activityVC.URLDic = note.userInfo;
            
        }else {
            FindViewController *findVC = [[FindViewController alloc] init];
            findVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:findVC animated:YES];
            [findVC release];
            findVC.URLDic = note.userInfo;
            
        }
        
    }];

    [[NSNotificationCenter defaultCenter] addObserverForName:@"PushLoginVC" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"loginState"] boolValue]) {
            MyOfUserDetail *detail = [[MyOfUserDetail alloc] init];
            detail.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:detail animated:YES];
            [detail release];
            detail.modelOfUser = [note.userInfo objectForKey:@"model"];
            
        }else {
            LoginVC *login = [[LoginVC alloc] init];
            login.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:login animated:YES];
            [login release];
        }
        
    }];

}

/** 创建装内容用collection装载 */
- (void)createSubViews {
    /** 设置显示属性 */
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    /** 每一个item的大小和屏幕一样 */
    flowLayout.itemSize = self.view.frame.size;
    /** 横向滚动 */
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    /** item直接的间距为0 */
    flowLayout.minimumLineSpacing = 0;
    
    /** 设置collectionView */
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,WIDTH, self.view.frame.size.height) collectionViewLayout:flowLayout];
    [flowLayout release];
    [self.view addSubview:_collectionView];
    [_collectionView release];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.bounces = NO;
    
  
    
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"poolOfCell"];
    
    /** 注册3种item类型 */
    [self.collectionView registerClass:[LikeOfCell class] forCellWithReuseIdentifier:@"poolOfLike"];
    /** 精选的cell */
    [self.collectionView registerClass:[CellOfRecommend class] forCellWithReuseIdentifier:@"poolOfRecommend"];
    /** 最新的cell */
    [self.collectionView registerClass:[NewsOfCell class] forCellWithReuseIdentifier:@"poolOfNews"];

    
#pragma mark - 轻扫手势
    UISwipeGestureRecognizer *swipeForRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipWith:)];
    [self.collectionView addGestureRecognizer:swipeForRight];
    [swipeForRight release];
    swipeForRight.direction = UISwipeGestureRecognizerDirectionRight;
    swipeForRight.delegate = self;

}

#pragma mark - swip轻扫属性
- (void)handleSwipWith:(UISwipeGestureRecognizer *)swip {
    if (swip.direction == UISwipeGestureRecognizerDirectionRight) {
        if (self.collectionView.contentOffset.x == 0) {
            [self.sideMenuViewController presentLeftMenuViewController];
        }
    }
    
}
#pragma mark - 设置能同时响应多个手势，正常返回No
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if ([otherGestureRecognizer.view class] == [UIScrollView class]) {
        return NO;
    }
    return YES;
}

#pragma mark - 返回的行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 3;
}
#pragma mark - 返回的样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    
    if (indexPath.item == 0) {
        CellOfRecommend *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfRecommend" forIndexPath:indexPath];
        
        
        return cell;
    
    }else if (indexPath.item == 1){
        
        LikeOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfLike" forIndexPath:indexPath];
        
        
        return cell;
        
    }else {
        NewsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfNews" forIndexPath:indexPath];
        
        
        return cell;
        
    }
}




#pragma mark - 创建naviController
- (void)createNaviController {
    self.view.backgroundColor = [UIColor redColor];
    
    self.sg = [[UISegmentedControl alloc] initWithItems:@[@"精选", @"关注", @"最新"]];
    self.navigationItem.titleView = self.sg;
    [_sg release];
    self.sg.frame = CGRectMake(0, 0, 0, 44);
    
    self.sg.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
    /** 设置字体选中时颜色 */
    NSDictionary *selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20],NSForegroundColorAttributeName: [UIColor grayColor]};
    [self.sg setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    /** 设置字体非选中时颜色 */
    NSDictionary *unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName: [UIColor lightGrayColor]};
    [self.sg setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    /** 这只初始选择项为0 */
    self.sg.selectedSegmentIndex = 0;
    
    /** 添加事件 */
    [self.sg addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    
    /** 设置左侧button属性 */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 20, 20);
    [leftButton setBackgroundImage:[UIImage imageNamed:@"saomiao"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:leftButton] autorelease];
    leftButton.tag = 100;
    
    /** 设置右侧button属性 */
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 20, 20);
    [rightButton setBackgroundImage:[UIImage imageNamed:@"sousuo"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightButton] autorelease];
    rightButton.tag = 101;
    
    
    self.grayLine = [[UIView alloc] init];
    [self.navigationController.navigationBar addSubview:_grayLine];
    [_grayLine release];
    
    self.grayLine.frame = CGRectMake(self.sg.frame.origin.x, 39, self.sg.frame.size.width / 3, 5);
    self.grayLine.layer.borderWidth = 3;
    self.grayLine.layer.borderColor = [UIColor grayColor].CGColor;
    self.grayLine.layer.cornerRadius = 2.5;
    self.grayLine.layer.masksToBounds = YES;
    
    
}

#pragma mark - segment点击方法
- (void)segmentAction:(UISegmentedControl *)sg {
    
    [self.collectionView setContentOffset:CGPointMake(sg.selectedSegmentIndex * WIDTH, 0) animated:YES];


}
#pragma mark - scrollView滚动的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sgWidth = self.sg.frame.size.width / 3.0f;
    self.grayLine.transform = CGAffineTransformMakeTranslation(scrollView.contentOffset.x / WIDTH * sgWidth, 0);
}

#pragma mark - collectionView滑动方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int page = scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width;
    self.sg.selectedSegmentIndex = page;
}

#pragma mark - navi左右button的点击事件
- (void)handleAction:(UIButton *)button {
    
    switch (button.tag) {
        case 100:{
            CaptrueViewController *capVC = [[CaptrueViewController alloc] init];
            capVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:capVC animated:YES];
            [capVC release];
            break;
        }
        case 101:{
            SearchViewController *searchVC = [[SearchViewController alloc] init];
            searchVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:searchVC animated:YES];
            [searchVC release];
            
            break;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
